package com.itheima.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.itheima.canal.config.RabbitMQConfig;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ZJ
 */
@CanalEventListener
public class SpuListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * spu 表更新
     * @param eventType
     * @param rowData
     */
    @ListenPoint(schema = "changgou_goods", table = {"tb_spu"})
    public void spuUp(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
        //改变前的列和值
        Map<String, String> beformap = new HashMap<>();
        List<CanalEntry.Column> beforeColumnsList = rowData.getBeforeColumnsList();
//        for (CanalEntry.Column column : beforeColumnsList) {
//            //某一列
//            String name = column.getName();
//            //值
//            String value = column.getValue();
//            beformap.put(name,value);
//        }
        // beforeColumnsList.forEach((column ->beformap.put(column.getName(),column.getValue())));
        beforeColumnsList.forEach((c -> beformap.put(c.getName(), c.getValue())));
        //改变后的列和值
        Map<String, String> aftermap = new HashMap<>();
        List<CanalEntry.Column> afterColumnsList = rowData.getAfterColumnsList();

        afterColumnsList.forEach((c -> aftermap.put(c.getName(), c.getValue())));

        if (beformap.get("is_marketable").equals("0") && aftermap.get("is_marketable").equals("1")) {

            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE, "", aftermap.get("id"));

        }
        //获取最新下架的商品 0-》1
        //如果下架状态修改前的1，修改后的是0，则属于上架操作
        if ("1".equals(beformap.get("is_marketable")) && "0".equals(aftermap.get("is_marketable"))) {
            System.out.println("监控到tb_spu表变化（下架操作），发送到mq");
            rabbitTemplate.convertAndSend("goods_down_exchange", "", aftermap.get("id"));
        }


        //获取最新审核通过商品 status 0->1
        if ("0".equals(beformap.get("status")) && "1".equals(aftermap.get("status"))) {
            //发送spuId到mq
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE, "", aftermap.get("id"));
        }

    }
}
